package com.yun.lc.dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class DBProvider {

    public static Connection getConn() {
        Connection conn = null;
        String strUrl = "jdbc:mysql://localhost:3306/jsp_first?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false"; // url连接串
        String strDBDriverType = "com.mysql.cj.jdbc.Driver"; // 数据库驱动类名
        String strUserName = "root"; // 用户名
        String strUserPsw = "lL123456789"; // 密码

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");  // 固定写法（反射）
            conn = DriverManager.getConnection(strUrl, strUserName, strUserPsw);
        } catch (Exception e) {
            System.out.println("JDBC获取数据库连接异常：" + e.getMessage());
        }
        return conn;
    }

    public static List<Map<String, Object>> query4ListMap(String strSql) {
        List<Map<String, Object>> lst = new ArrayList<>();
        try (
             Connection conn = getConn();
             Statement st = conn.createStatement();
             ResultSet rs = st.executeQuery(strSql);
        ) {
            Map<String, Object> mapEachRow = null;
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                mapEachRow = new LinkedHashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = rsmd.getColumnLabel(i);  // 包含别名
                    Object columnValue = rs.getObject(columnName);
                    mapEachRow.put(columnName, columnValue);
                }
                lst.add(mapEachRow);
            }

        } catch (Exception e) {
            System.out.println("JDBC查询数据库操作异常：" + e.getMessage());
        }
        return lst;
    }

}